<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { EmployeeVO } from '#/api/company/audience/model';
import type { PersonalFavoriteVO } from '#/api/company/favorite/personal/model';

import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { Fallback } from '@vben/common-ui';
import { getVxePopupContainer } from '@vben/utils';

import { Card, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { employeePage } from '#/api/company/audience';
import { personalFavoriteRemoveMember } from '#/api/company/favorite/personal';
import { columns, querySchema } from '#/views/company/audience/data';

defineOptions({
  name: 'PersonalFavoritePanel',
  inheritAttrs: false,
});

const props = defineProps<{ favorite?: PersonalFavoriteVO }>();

/**
 * 下面按钮点击后会触发的事件
 */
defineEmits<{ reload: [] }>();

const currentFavorite = ref<any>();

const tableTitle = computed(() => {
  return `收藏夹 “${currentFavorite.value?.name}” - 人员列表`;
});

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-3',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: false,
  },
  columns: (columns as any[])
    .map((column) => {
      if (column.field === 'action') {
        column.width = 130;
      }
      return column;
    })
    .filter((column) => !['mobile', 'provinceName'].includes(column.field)),
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        if (!currentFavorite.value) return { rows: [], total: 0 };

        return await employeePage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          favoriteId: currentFavorite.value.id,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // 表格全局唯一表示 保存列配置需要用到
  id: 'favorite-personal-manage-index',
  showOverflow: false,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  separator: false, // 移除分隔条
  gridEvents: {
    // 需要控制不同的事件 radio也会触发checkbox事件
    checkboxChange: checkBoxEvent,
    checkboxAll: checkBoxEvent,
  },
});

const loading = ref(false);

async function handleLoadInfo(favorite: PersonalFavoriteVO | undefined) {
  try {
    if (!favorite) return null;
    loading.value = true;
    currentFavorite.value = favorite;
    await nextTick();
    await tableApi?.query();
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
}

watch(() => props.favorite, handleLoadInfo);

function checkBoxEvent() {
  // const records = tableApi.grid.getCheckboxRecords();
}

async function handleRemove(row: any) {
  await personalFavoriteRemoveMember({
    employeeIds: [row.id],
    favoriteId: currentFavorite.value?.id as string,
  });
  await tableApi?.query();
}

// 查看详情
const router = useRouter();

function handleDetails(row: EmployeeVO) {
  router.push(`/company/audience/details/${row.id}`);
}

onMounted(() => {
  // console.log('当前收藏夹：');
});
onUnmounted(() => (currentFavorite.value = undefined));
</script>

<template>
  <Card
    v-if="currentFavorite"
    :body-style="{ overflowY: 'auto', height: '100%' }"
    class="thin-scrollbar flex-1 overflow-y-hidden"
    size="small"
  >
    <BasicTable>
      <template #table-title>
        <main-title :text="tableTitle" />
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['employee:manager:query']"
            @click="handleDetails(row)"
          >
            详情
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确定仅从收藏夹中移除？"
            @confirm="handleRemove(row)"
          >
            <ghost-button
              v-access:code="['employee:favorite:removeMember']"
              danger
              @click.stop=""
            >
              移除
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
  </Card>
  <Fallback v-else title="点击左侧收藏夹查看" />
</template>
